#include "MainWindow.h"
#include "Model.h"

#include <QMenuBar>
#include <QVBoxLayout>
#include <QToolBar>
#include <QLabel>
#include <QTreeView>
#include <QDebug>
#include <QListView>
#include <QSlider>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_model(nullptr)
    , m_selectedAlbumIndex(-1)
    , m_spriteSizeScale(1.0)
{
    // pre data init
    m_model = new Model();

    // ui init
    QMenuBar *menuBar = this->menuBar();

    QMenu *fileMenu = new QMenu(this);
    fileMenu->setTitle("文件");
    QAction *openFileAction = new QAction("打开", this);
    fileMenu->addAction(openFileAction);
    QAction *exportAction = new QAction("导出图片和中心信息", this);
    fileMenu->addAction(exportAction);
    menuBar->addMenu(fileMenu);

    QMenu *helpMenu = new QMenu(this);
    helpMenu->setTitle("帮助");
    QAction *aboutAction = new QAction("关于", this);
    helpMenu->addAction(aboutAction);
    menuBar->addMenu(helpMenu);

    // main layout
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setContentsMargins(0, 0, 0, 0);

    QWidget *mainWidget = new QWidget(this);
    mainWidget->setLayout(mainLayout);

    setCentralWidget(mainWidget);

    QHBoxLayout *contentLayout = new QHBoxLayout;
    contentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->setSpacing(0);
    mainLayout->addLayout(contentLayout);

    // left content
//    contentLayout->addSpacing(3);
    QVBoxLayout *leftContentLayout = new QVBoxLayout;
    leftContentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->addLayout(leftContentLayout);

    leftContentLayout->addSpacing(5);
    QLabel *leftContentTitleLabel = new QLabel(this);
    leftContentTitleLabel->setText("相册");
    leftContentLayout->addWidget(leftContentTitleLabel, 0, Qt::AlignLeft | Qt::AlignTop);

    leftContentLayout->addSpacing(5);
    QListView *itemListView = new QListView(this);
    itemListView->setIconSize(QSize(30, 30));
    itemListView->setWordWrap(true);
    itemListView->setEditTriggers(QTreeView::EditTrigger::NoEditTriggers);
//    itemTreeView->setStyleSheet("background-color:yellow");
    leftContentLayout->addWidget(itemListView, 0, Qt::AlignLeft);

    QStandardItemModel *itemListViewModel = new QStandardItemModel(this);
    itemListView->setModel(itemListViewModel);

    // right content
    contentLayout->addSpacing(3);
    QVBoxLayout *rightContentLayout = new QVBoxLayout;
    rightContentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->addLayout(rightContentLayout, 1);

    // map title layout
    rightContentLayout->addSpacing(5);
    QLabel *rightContentTitleLabel = new QLabel(this);
//    rightContentTitleLabel->setStyleSheet("background-color:red");
    rightContentTitleLabel->setText("精灵列表");
    rightContentLayout->addWidget(rightContentTitleLabel, 0, Qt::AlignLeft | Qt::AlignVCenter);

    QListView *spriteListView = new QListView(this);
    spriteListView->setIconSize(QSize(30, 30));
    spriteListView->setMaximumHeight(this->height() / 2);
    spriteListView->setWordWrap(true);
    spriteListView->setEditTriggers(QTreeView::EditTrigger::NoEditTriggers);
//    itemTreeView->setStyleSheet("background-color:yellow");
    rightContentLayout->addWidget(spriteListView);

    QStandardItemModel *spriteListViewModel = new QStandardItemModel(this);
    spriteListView->setModel(spriteListViewModel);

    QHBoxLayout *spriteViewTitleLayout = new QHBoxLayout;
    spriteViewTitleLayout->setContentsMargins(0, 0, 0, 0);
    spriteViewTitleLayout->setSpacing(0);
    rightContentLayout->addLayout(spriteViewTitleLayout);

    QLabel *spriteViewTitleLabel = new QLabel(this);
    spriteViewTitleLabel->setText("精灵视图");
    spriteViewTitleLayout->addWidget(spriteViewTitleLabel, 0, Qt::AlignLeft);

    spriteViewTitleLayout->addSpacing(40);
    QLabel *spriteSizeScaleLabel = new QLabel(this);
    spriteSizeScaleLabel->setText("放大率：");
    spriteViewTitleLayout->addWidget(spriteSizeScaleLabel, 0, Qt::AlignLeft);

    QSlider *spriteSizeScaleSlider = new QSlider(this);
    spriteSizeScaleSlider->setFixedWidth(200);
    spriteSizeScaleSlider->setRange(10, 100);
    spriteSizeScaleSlider->setOrientation(Qt::Orientation::Horizontal);
    spriteViewTitleLayout->addWidget(spriteSizeScaleSlider, 0, Qt::AlignLeft);

    spriteViewTitleLayout->addSpacing(5);
    QLabel *spriteSizeScaleValueLabel = new QLabel(this);
    spriteSizeScaleValueLabel->setText("1.0");
    spriteViewTitleLayout->addWidget(spriteSizeScaleValueLabel, 0, Qt::AlignLeft);
    spriteViewTitleLayout->addStretch(1);

    QFrame *spriteView = new QFrame(this);
    spriteView->setFrameShape(QFrame::Shape::Box);
    QVBoxLayout *spriteViewLayout = new QVBoxLayout;
    spriteViewLayout->setContentsMargins(0, 0, 0, 0);
    spriteView->setLayout(spriteViewLayout);
    rightContentLayout->addWidget(spriteView, 1);

    QLabel *spriteViewLabel = new QLabel(spriteView);
    spriteViewLabel->setScaledContents(true);
    spriteViewLayout->addWidget(spriteViewLabel, 0, Qt::AlignCenter);

    // connect
    connect(fileMenu, &QMenu::triggered, this, [=](QAction *action) {
        if (action == openFileAction) {
            this->setWindowTitle("NpkEditor（加载中...）");
            const QString &filePath = m_model->OpenLoadNpkFileDlg();
            QFileInfo fInfo(filePath);
            this->setWindowTitle("NpkEditor [" + fInfo.fileName() + "]");
        }
        if (action == exportAction) {
            const QString &windowTitleStr = windowTitle();
            this->setWindowTitle("NpkEditor（导出中...）");
            m_model->OpenExportFileDlg();
            this->setWindowTitle(windowTitleStr);
        }
    });

    connect(m_model, &Model::LoadNpkFinished, this, [=] {
        itemListViewModel->clear();
        const QList<Album> &albumList = m_model->GetAlbumList();
        for (const Album &album : albumList) {
            QFileInfo fInfo(album.Path);
            QStandardItem *item = new QStandardItem(fInfo.fileName());
            itemListViewModel->appendRow(item);
        }

        if (albumList.size()) {
            const QModelIndex &currentIndex = itemListViewModel->index(0, 0);
            itemListView->setCurrentIndex(currentIndex);
            Q_EMIT itemListView->clicked(currentIndex);
        }
    });

    connect(itemListView, &QListView::clicked, this, [=](const QModelIndex &modelIndex) {
        m_selectedAlbumIndex = modelIndex.row();
        const QModelIndex lastSelectedSpriteListViewIndex = spriteListView->currentIndex();
        const QList<Album> &albumList = m_model->GetAlbumList();
        const Album &selectedAlbum = albumList.at(m_selectedAlbumIndex);
        const QList<SpriteStruct> &spriteList = selectedAlbum.SpriteList;
        spriteListViewModel->clear();
        for (const SpriteStruct &sprite : spriteList) {
            bool isLink = sprite.Type == SpriteTypeEnum::Link;
            const QString itemTitle = QString("%1, w: %2, h: %3, x: %4, y: %5, isLink: %6")
                    .arg(sprite.Index).arg(sprite.Width).arg(sprite.Height)
                    .arg(sprite.X).arg(sprite.Y).arg(isLink);
            QStandardItem *item = new QStandardItem(itemTitle);
            spriteListViewModel->appendRow(item);
        }

        if (spriteList.size()) {
            QModelIndex currentIndex = spriteListViewModel->index(0, 0);
            if (lastSelectedSpriteListViewIndex.row() >= 0 &&
                lastSelectedSpriteListViewIndex.row() < spriteListViewModel->rowCount())
            {
                currentIndex = spriteListViewModel->index(lastSelectedSpriteListViewIndex.row(), 0);
            }
            spriteListView->setCurrentIndex(currentIndex);
            Q_EMIT spriteListView->clicked(currentIndex);
        }
    });

    connect(spriteListView, &QListView::clicked, this, [=](const QModelIndex &modelIndex) {
        int selectedSpriteIndex = modelIndex.row();
        const QList<Album> &albumList = m_model->GetAlbumList();
        const Album &selectedAlbum = albumList.at(m_selectedAlbumIndex);
        const QList<SpriteStruct> &spriteList = selectedAlbum.SpriteList;

        SpriteStruct sprite = spriteList.at(selectedSpriteIndex);
        bool isLink = sprite.Type == SpriteTypeEnum::Link;
        if (isLink) {
            sprite = spriteList.at(sprite.LinkIndex);
        }
        m_currentSprite = sprite;
        spriteViewLabel->setFixedSize(m_currentSprite.Width * m_spriteSizeScale,
                                      m_currentSprite.Height * m_spriteSizeScale);

        const QImage &img = m_model->GetSpriteImg(selectedAlbum, sprite);
        spriteViewLabel->setPixmap(QPixmap::fromImage(img));
    });

    connect(spriteSizeScaleSlider, &QSlider::valueChanged, this, [=](int value) {
        qDebug() << value;
        // float lastSpriteSizeScale = m_spriteSizeScale;
        m_spriteSizeScale = 10 * (value / 100.0);
        spriteSizeScaleValueLabel->setText(QString::number(m_spriteSizeScale, 'g', 2));

        spriteViewLabel->setFixedSize(m_currentSprite.Width * m_spriteSizeScale,
                                      m_currentSprite.Height * m_spriteSizeScale);
    });

    // post init
}

MainWindow::~MainWindow()
{
}
